<template>
  <wd-popup
    :model-value="show"
    :custom-style="popupStyle"
    position="bottom"
    transition="slide-up"
    @update:model-value="$emit('update:show', $event)"
  >
    <view class="close-button" @click="$emit('update:show', false)">
      <wd-icon name="close" size="36rpx" color="#333333" />
    </view>
    <template v-if="currentProduct && product">
      <view class="header">
        <v-image
          height="110rpx"
          width="110rpx"
          border-radius="16rpx"
          mode="aspectFill"
          :src="currentProduct?.image"
        />
        <view class="product-price">
          <view class="label">
            到手价
          </view>
          <v-price size="56rpx" :price="currentProduct.sell_price" />
          <!-- <view class="label">
            起
          </view> -->
          <view v-if="currentProduct.market_price" class="market-price">
            {{ `¥${currentProduct.market_price.toFixed(2)}` }}
          </view>
        </view>
      </view>

      <scroll-view scroll-y style="flex: 1; height: 0">
        <view class="product-select-block" style="gap: 24rpx">
          <view
            v-for="(spec, index) in displaySpecList"
            :key="index"
            class="spec-group"
          >
            <view class="spec-title">
              {{ spec.name }}
            </view>
            <view class="spec-list">
              <view
                v-for="(specValue, valueIndex) in spec.valueList"
                :key="valueIndex"
                class="spec-item"
                :class="{
                  active: specValue.selecting,
                  'sold-out': specValue.soldOut
                }"
                @click="selectSpec(spec.name, specValue.value)"
              >
                <text class="text">
                  {{ specValue.value }}
                </text>
              </view>
            </view>
          </view>
          <view class="product-select-item">
            <view class="label">
              库存数量
            </view>
            <view class="content">
              {{ currentProduct.inventory || '无货' }}
            </view>
          </view>
          <view class="product-select-item">
            <view class="label">
              变更数量
            </view>
            <view class="content">
              {{ cartProduct?.quantity }}
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="submit-button-container">
        <v-button
          type="primary"
          :custom-style="{ height: '80rpx' }"
          :disabled="!!disabledText"
          @click="submitHandle"
        >
          {{ disabledText ? disabledText : '确定' }}
        </v-button>
      </view>
    </template>
    <template v-else>
      <v-loading-block />
    </template>
  </wd-popup>
</template>

<script setup lang="ts">
const popupStyle = computed(() => {
  const list: string[] = [];
  list.push('padding-top:24rpx');
  list.push('background:#f5f6fa');
  // #ifdef MP-ALIPAY
  list.push('max-height:65vh');
  // #endif
  // #ifndef MP-ALIPAY
  list.push('height:65vh');
  // #endif
  list.push('display:flex');
  list.push('flex-direction:column');
  list.push('border-radius: 16rpx 16rpx 0 0');
  return list.join(';');
});

const props = defineProps<{
  show: boolean;
  cartProduct?: CartVO;
}>();

const emits = defineEmits<{
  'update:show': [val: boolean];
  refresh: [];
}>();

const cartProduct = toRef(props, 'cartProduct');
const product = ref<SpuVO>();
const getProductDetails = async () => {
  if (!cartProduct.value) return;
  const response = await $api.getSearchIdDetail(cartProduct.value.spu_id);
  switch (response.__error) {
    case undefined:
      product.value = response.data;
      break;
    default:
      emits('update:show', false);
  }
};

const selectingSpec = ref<{ name: string; value: string }[]>([]);
const selectSpec = (name: string, value: string) => {
  const newList = selectingSpec.value.concat([]);
  const index = newList.findIndex((spec) => spec.name === name);
  if (index >= 0) {
    newList.splice(index, 1, { name, value });
  } else {
    newList.push({ name, value });
  }
  const list = product.value?.sku_list ?? [];
  // 直接有这个sku
  const target = list.find((sku) =>
    sku.spec_info.every((skuSpec) =>
      newList.some(
        (selectingSpec) =>
          selectingSpec.name === skuSpec.name &&
          selectingSpec.value === skuSpec.value
      )
    )
  );
  if (target) {
    selectingSpec.value = newList;
    return;
  }
  // 没有这个sku，尝试找一个有该规格的
  const secondTarget = list.find((sku) =>
    sku.spec_info.some(
      (skuSpec) => skuSpec.name === name && skuSpec.value === value
    )
  );
  if (secondTarget) {
    selectingSpec.value = secondTarget.spec_info.map((spec) => ({
      name: spec.name,
      value: spec.value
    }));
  } else {
    // 没有有这个规格的sku，无效按钮
  }
};
const initDefaultSelectingSpec = () => {
  if (!cartProduct.value) return;
  selectingSpec.value = cartProduct.value.spec_info.map((spec) => ({
    name: spec.name,
    value: spec.value
  }));
};
watch(
  () => props.show,
  (val) => {
    if (val) {
      product.value = undefined;
      initDefaultSelectingSpec();
      getProductDetails();
    }
  }
);

const checkSkuInventory = (target: { name: string; value: string }[]) => {
  const item = product.value?.sku_list.find((sku) =>
    sku.spec_info.every((skuSpec) =>
      target.some(
        (selectingSpec) =>
          selectingSpec.name === skuSpec.name &&
          selectingSpec.value === skuSpec.value
      )
    )
  );
  return !!item && item.sale_status && item.inventory > 0;
};
const displaySpecList = computed(() => {
  if (!product.value?.spec_info) return [];
  const list: {
    name: string;
    valueList: { value: string; selecting: boolean; soldOut: boolean }[];
  }[] = [];
  const lastIndex = selectingSpec.value.length - 1;
  for (let i = 0; i < product.value.spec_info.length; i += 1) {
    const spec = product.value.spec_info[i];
    const rest = selectingSpec.value.filter(
      (selecting) => selecting.name !== spec.name
    );
    list.push({
      name: spec.name,
      valueList: spec.value_list.map((value) => ({
        value,
        selecting: selectingSpec.value.some(
          (selecting) =>
            selecting.name === spec.name && selecting.value === value
        ),
        soldOut:
          i === lastIndex &&
          !checkSkuInventory([...rest, { name: spec.name, value }])
      }))
    });
  }
  return list;
});
const currentProduct = computed(() => {
  if (!product.value?.sku_list) return undefined;
  const sku = product.value.sku_list.find((sku) =>
    sku.spec_info.every((skuSpec) =>
      selectingSpec.value.some(
        (selectingSpec) =>
          selectingSpec.name === skuSpec.name &&
          selectingSpec.value === skuSpec.value
      )
    )
  );
  return sku;
});

const removeOriginalProduct = async () => {
  if (!cartProduct.value) return;
  const response = await $api.postCartRemove([
    { cart_id: cartProduct.value.id }
  ]);
  switch (response.__error) {
    case undefined:
      return true;
    default:
      return false;
  }
};
const addToCartHandle = async () => {
  if (!currentProduct.value) return;
  if (!cartProduct.value) return;
  uni.showLoading({ mask: true });
  const response = await $api.postCartAdd({
    sku_id: currentProduct.value.id,
    quantity: cartProduct.value.quantity
  });
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      return true;
    default:
      return false;
  }
};

const disabledText = computed(() => {
  if (!currentProduct.value || !cartProduct.value) return '无效商品';
  if (!currentProduct.value.inventory) return '无库存';
  if (currentProduct.value.inventory < cartProduct.value.quantity) {
    return '库存不足';
  }
  return '';
});
const submitHandle = async () => {
  if (currentProduct.value?.id === cartProduct.value?.sku_id) {
    emits('update:show', false);
    return;
  }
  uni.showLoading({ mask: true });
  let result = await addToCartHandle();
  if (!result) return;
  result = await removeOriginalProduct();
  uni.hideLoading();
  if (result) {
    uni.showToast({ title: '修改成功', icon: 'none' });
    emits('refresh');
    emits('update:show', false);
  }
};
</script>

<style lang="scss" scoped>
.close-button {
  position: absolute;
  top: 36rpx;
  right: 36rpx;
  z-index: 1;
}

.header {
  display: flex;
  align-items: center;
  margin: 0 24rpx 24rpx;
  gap: 24rpx;
  .product-price {
    display: flex;
    align-items: baseline;
    gap: 0 8rpx;
    margin-top: 30rpx;
    white-space: nowrap;
    .label {
      color: #ff2f3b;
      flex-shrink: 0;
    }
    .market-price {
      color: #999999;
      text-decoration: line-through;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      white-space: nowrap;
    }
  }
}

.product-select-block {
  margin: 0 24rpx 24rpx;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 12rpx;
  .address-item {
    display: flex;
    align-items: center;
    gap: 24rpx;
    .address-content {
      flex: 1;
      min-width: 0;
      .address-main {
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
      }
      .address-sub {
        color: #999999;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        display: inline-flex;
        gap: 0 8rpx;
      }
    }
    .alipay-holder {
      color: #007afe;
      flex: 1;
      min-width: 0;
    }
    .weixin-holder {
      color: #07c160;
    }
  }

  .spec-group {
    margin-bottom: 12rpx;
    .spec-title {
      font-weight: bold;
      margin-bottom: 24rpx;
    }
    .spec-list {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx 24rpx;
      .spec-item {
        position: relative;
        max-width: calc(100% - 50rpx);
        box-sizing: border-box;
        line-height: 60rpx;
        border: 1px solid #f5f6fa;
        background-color: #f5f6fa;
        border-radius: 16rpx;
        padding: 0 24rpx;
        transition:
          border 0.3s,
          background-color 0.3s,
          color 0.3s;
        .text {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: break-all;
        }
        &.active {
          border: 1px solid #ff2f3b;
          background-color: rgba(255, 47, 59, 0.1);
          .text {
            color: #ff2f3b;
          }
        }
        &.sold-out {
          border: 1px solid rgba(245, 246, 250, 0.5);
          background-color: rgba(245, 246, 250, 0.5);
          .text {
            color: rgba(51, 51, 51, 0.5);
          }
          &::after {
            content: '售罄';
            position: absolute;
            z-index: 1;
            right: 0;
            top: 0;
            transform: translate(80%, -50%);
            background-color: #cccccc;
            border-radius: 18rpx 18rpx 18rpx 0;
            height: 36rpx;
            width: 80rpx;
            font-size: 24rpx;
            line-height: 36rpx;
            color: white;
            font-weight: 300;
            text-align: center;
          }
        }
        &.sold-out.active {
          border: 1px solid #cccccc;
        }
      }
    }
  }

  .product-select-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24rpx;
    height: 60rpx;
    .label {
      flex-shrink: 0;
    }
    .content {
      flex: 1;
      min-width: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 12rpx;
    }
  }

  .shipping-item {
    display: flex;
    align-items: center;
    gap: 24rpx;
    .main {
      font-weight: bold;
      flex: 1;
      min-width: 0;
    }
    .sub {
      color: #999999;
    }
  }
}

.submit-button-container {
  margin: 0 24rpx 24rpx;
  padding: 10rpx 0;
}
</style>
